package com.wlyuan.gateway.filter;

import com.wlyuan.gateway.config.RefererProperties;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.List;

/**
 * @author
 *
 */
@Slf4j
@Component
@RequiredArgsConstructor
public class RefererListFilter implements GlobalFilter, Ordered {
    private final RefererProperties refererProperties;

    private boolean isRefererListIp(String ip,String requestUrl) {
        // 是否全局变量判断，如果是，则需要
        boolean state = refererProperties.isOverAllState();
        if(state) {
            if(StringUtils.isNotBlank(ip)) {
                List<String> referList = refererProperties.getOverAllowedReferer();
                if (CollectionUtils.isEmpty(referList)) {
                    return true;
                }
                for (String refer : referList) {
                    if (ip.startsWith(refer)) {
                        return true;
                    }
                }
            }
            return false;
        }else{
            if(!CollectionUtils.isEmpty(refererProperties.getSingleAllowedReferer())){
                List<String> singleAllowed = refererProperties.getSingleAllowedReferer().get(requestUrl);
                if(singleAllowed!=null){
                    boolean isMatched = false;
                    if(StringUtils.isNotBlank(ip)) {
                        for (String refer : singleAllowed) {
                            if (ip.startsWith(refer)) {
                                isMatched = true;
                                break;
                            }
                        }
                    }
                    return isMatched;
                }
            }
            return true;
        }
    }

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        String referer = exchange.getRequest().getHeaders().getFirst("referer");
        String requestUrl = exchange.getRequest().getURI().getPath();
        if (!isRefererListIp(referer,requestUrl)) {
            exchange.getResponse().setStatusCode(HttpStatus.FORBIDDEN);
            logger.debug("非Referer,拒绝访问！:requestUrl, currentReferer:{}",requestUrl, referer);
            String data = "请求被禁止!";
            DataBuffer wrap = exchange.getResponse().bufferFactory().wrap(data.getBytes());
            return exchange.getResponse().writeWith(Mono.just(wrap));
        }
        return chain.filter(exchange);
    }


    @Override
    public int getOrder() {
        return 0;
    }
}
